/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 版本: 苏州公安统一用户管理平台1.0
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名:DeptManagerController.java
 * <p>
 * 类产生时间: 2012-5-29 上午12:53:18
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 苏州公安统一用户管理平台
 * <p>
 * 所在部门: 电信/国土——技术二部
 * <p>
 * <p>
 */
package com.oceansoft.core.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.hui.platform.system.utility.StringUtil;
import com.oceansoft.core.common.constant.Constant;
import com.oceansoft.core.common.constant.ConstantMap;
import com.oceansoft.core.common.util.CommonUtilCache;
import com.oceansoft.core.common.util.Pagination;
import com.oceansoft.core.domain.SysDept;
import com.oceansoft.core.domain.SysOperLog;
import com.oceansoft.core.domain.SysUser;
import com.oceansoft.core.service.ISysDeptService;

/**
 * 部门管理控制器
 *
 * @author acer
 *
 */
@Controller
@RequestMapping("/dept")
public class DeptManagerController {

	@Autowired
	private ISysDeptService sysDeptService;

	/**
	 * 进入部门管理首页
	 *
	 * @return
	 */
	@RequestMapping("/index.html")
	public String gotoDeptIndex() {
		return "dept/index";
	}

	@RequestMapping("/tree")
	public void getDeptTree(ModelMap model, HttpServletRequest request) {
		String deptId = request.getParameter("deptId");
		//new add
		SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
		Map<String,Object> roles =  (Map<String,Object>) request.getSession().getAttribute(
				Constant.SESSION_ROLOES);
		boolean isadmin = roles.containsKey((String)((ServletContext)CommonUtilCache.getItem("ctx")).getAttribute("admin_roleid"));
		boolean deptadmin = roles.containsKey((String)((ServletContext)CommonUtilCache.getItem("ctx")).getAttribute("dept_roleid"));
		if(StringUtil.isNull(deptId))
		{

			//管理员查看所有分局,政治部查询自己分局
			if(isadmin)
			{
				deptId = "320600";
			}
			else if(deptadmin)
			{
				deptId = user.getDeptId().substring(0,6);
			}
			else
			{
				deptId = user.getDeptId();;
			}
		}
		List<SysDept> list = sysDeptService.findDeptTree(deptId,user,"1");
		model.addAttribute("data", list);
	}
	/*@RequestMapping("/flip")
	public String flipWeb(ModelMap model, HttpServletRequest request) {
		String deptId = request.getParameter("deptId");
		model.addAttribute("deptId", deptId);
		return "dept/open_sub_tree";
	}*/
	@RequestMapping("/subtree")
	public void getSubDeptTree(ModelMap model, HttpServletRequest request) {
		String dw1 = request.getParameter("dw1");
		String deptId = request.getParameter("deptId");
		List<SysDept> listdept = sysDeptService.findSubDeptTree(dw1,deptId);
		List<SysDept> list = new ArrayList<SysDept>();
		SysDept deptTop = sysDeptService.findByDeptId(dw1);
		for(SysDept lit:listdept)
		{
			if(!"320500".equals(lit.getDeptId()))
			{
				//lit.setAlias(lit.getAlias().replace(deptTop.getAlias(), ""));
			}
			list.add(lit);
		}
		model.addAttribute("data", list);
	}
	/**
	 * 设置树可以拖动的
	 *
	 * @param model
	 * @param request
	 */
	@RequestMapping("/dragtree")
	public void getGragTree(ModelMap model, HttpServletRequest request) {
		String deptId = request.getParameter("deptId");
		//new add

		SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
		//user.setDeptId(user.getDeptId().replace("320500","320600"));
		Map<String,Object> roles =   (Map<String,Object>) request.getSession().getAttribute(
				Constant.SESSION_ROLOES);
		boolean isadmin = roles.containsKey((String)((ServletContext)CommonUtilCache.getItem("ctx")).getAttribute("admin_roleid"));
		boolean deptadmin = roles.containsKey((String)((ServletContext)CommonUtilCache.getItem("ctx")).getAttribute("dept_roleid"));
		String isparent="0";
		if(StringUtil.isNull(deptId))
		{
			//管理员查看所有分局,政治部查询自己分局
			if(isadmin)
			{
				deptId = "320000";
			}
			else if(deptadmin)
			{
				deptId = user.getDeptId();
			}
			isparent="1";
		}
		List<SysDept> list = sysDeptService.findDeptTree(deptId,user,isparent);
		List<SysDept> list2 = new ArrayList<SysDept>();
		for (SysDept dept : list) {
			dept.setDrag(true);
			list2.add(dept);
		}
		model.addAttribute("data", list2);
	}

	@RequestMapping("/autocomplete")
	public void getDeptByJpin(ModelMap model, HttpServletRequest request) {
		String jpin = request.getParameter("jpin");
		List<SysDept> list = sysDeptService.findByJpin(jpin);
		model.addAttribute("depts", list);
	}
	@RequestMapping("/alldeptautocomplete")
	public void getAllDeptByJpin(ModelMap model, HttpServletRequest request) {
		String jpin = request.getParameter("jpin");
		List<SysDept> list = sysDeptService._findByJpin(jpin);
		model.addAttribute("depts", list);
	}

	@RequestMapping("/autocompdept2")
	public void getDeptBydw2(ModelMap model, HttpServletRequest request) {
		String dw1 = request.getParameter("dw1");
		String dw2 = request.getParameter("dw2");
		List<SysDept> list =new ArrayList<SysDept>();
		if(null!=dw1&&!"".equals(dw1)&&null!=dw2&&!"".equals(dw2)){
			list = sysDeptService.findByDw1AndDw2(dw1,dw2);}
		model.addAttribute("depts", list);
	}
	@RequestMapping("/getdeptIdbyalias")
	public void findDeptByAlias(ModelMap model,HttpServletRequest request){
		String alias = request.getParameter("alias");
		String deptId = sysDeptService.findDeptByAlias(alias);
		model.addAttribute("deptId",deptId);
	}

	/**
	 * 跳转到新增部门页面
	 *
	 * @return
	 */
	@RequestMapping("/adddept/{parentId}.html")
	public String goToAddDept(ModelMap modelMap, @PathVariable("parentId") String parentId) {
		List<SysDept> list = sysDeptService.findDeptById(parentId);
		SysDept dept = null;
		if (list.size() != 0)
			dept = list.get(0);
		modelMap.addAttribute("dept", dept);
		return "dept/adddept";
	}

	/**
	 * 跳转到编辑部门页面
	 *
	 * @return
	 */
	@RequestMapping("/edit/{deptId}.html")
	public String goToEditDept(ModelMap modelMap, @PathVariable("deptId") String deptId) {
		List<SysDept> list = sysDeptService.findDeptByDeptId(deptId);
		SysDept dept = null;
		if (list.size() != 0)
			dept = list.get(0);
		modelMap.addAttribute("dept", dept);
		return "dept/edit";
	}

	/**
	 * 获取部门列表
	 *
	 * @param model
	 *            json 对象
	 */
	@RequestMapping("/getAllDept")
	public void loadAllDept(ModelMap model, HttpServletRequest request) {
		SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
		String id = request.getParameter("deptId");
		List<SysDept> list;
		if (null == id) {
			list = sysDeptService.findAllDept(request.getContextPath());
			model.addAttribute("data", list);
		} else {
			list = sysDeptService.findDeptByPid(id);
			model.addAttribute("data", list);
		}
		model.addAttribute("deptId", user.getDeptId());
		// model.addAttribute(Constant.LOG_RECORD, new SysOperLog(Constant.READ,
		// "查看部门树", ConstantMap.MODUAL_SYS_MGR,
		// ConstantMap.list2String(list)));
	}

	/**
	 * 获取部门列表,管理员后台
	 *
	 * @param model
	 *            json 对象
	 */
	@RequestMapping("/getbackdept")
	public void loadBackDept(ModelMap model, HttpServletRequest request) {
		SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
		String deptId = request.getParameter("deptId");
		List<Object> list = sysDeptService.findBackTree(deptId, user.getPoliceNum(), request.getContextPath());
		if (list.size() > 0) {
			model.addAttribute("data", list.get(0));
			model.addAttribute("manageDept", list.get(1));
		}
		model.addAttribute("deptId", user.getDeptId());
		// List<SysDept> depts = (List<SysDept>) list.get(0);
		// model.addAttribute(Constant.LOG_RECORD, new SysOperLog(Constant.READ,
		// "查看部门树", ConstantMap.MODUAL_SYS_MGR,
		// ConstantMap.list2String(depts)));
	}

	/**
	 * 通过部门编号获取部门信息
	 *
	 * @param id
	 *            部门编号
	 * @return string
	 */
	@RequestMapping(value = "/query/{deptId}/{pageIndex}/{deep}.html")
	public String getDeptByDeptId(@PathVariable("deptId") String deptId, @PathVariable("pageIndex") int pageIndex,
								  @PathVariable("deep") int deep, ModelMap model) {
		model.addAttribute("deptId", deptId);
		int length = 2 * deep + 4;
		deptId = deptId.substring(0, length);
		Pagination<SysDept> page = sysDeptService.findDeptByPagination(deptId, pageIndex);
		model.addAttribute("page", page);
		model.addAttribute("deep", deep);
		// model.addAttribute(Constant.LOG_RECORD, new SysOperLog(Constant.READ,
		// "查看部门列表", ConstantMap.MODUAL_SYS_MGR,
		// ConstantMap.list2String(page.getList())));
		return "dept/dept_list";
	}

	@RequestMapping(value = "/fuzzyQuery/{pageIndex}.html")
	public String fuzzyQuery(ModelMap model, @PathVariable("pageIndex") int pageIndex, HttpServletRequest request) {
		String deptId = request.getParameter("deptId");
		String deptName = request.getParameter("deptName");
		/**
		 * if (deptName != null && deptName.length() != 0) { deptName = new
		 * String(deptName.getBytes("iso-8859-1"), "UTF-8"); }
		 */
		Map<String, String> params = new HashMap<String, String>();
		if (deptId != null && !"".equals(deptId.trim()))
			params.put("deptId", deptId);
		if (deptName != null && !"".equals(deptName.trim()))
			params.put("name", deptName);
		Pagination<SysDept> page = sysDeptService.fuzzyQuery(params, pageIndex);
		model.addAttribute("page", page);
		model.addAttribute("deptid", deptId);
		model.addAttribute("deptName", deptName);
		// model.addAttribute(Constant.LOG_RECORD, new SysOperLog(Constant.READ,
		// "查看部门列表", ConstantMap.MODUAL_SYS_MGR,
		// ConstantMap.list2String(page.getList())));
		return "dept/dept_list";
	}

	@RequestMapping("/getUserInResult")
	public ModelAndView getUserInResult(@RequestParam("deptId") String deptId, @RequestParam("id") String id,
										@RequestParam("name") String name) {
		ModelAndView model = new ModelAndView("dept/sysUserInfo");
		return model;
	}

	@RequestMapping("/add")
	// public void addDept(ModelMap modelMap, SysDept dept,
	// @ModelAttribute(Constant.LOGIN_USER) SysUser user) {
	public void addDept(ModelMap modelMap, SysDept dept) {
		int result = sysDeptService.addDept(dept);
		if (result == 1)
			modelMap.addAttribute("success", "1");
		else
			modelMap.addAttribute("success", result);
		modelMap.addAttribute(Constant.LOG_RECORD, new SysOperLog(Constant.CREATE, 1 == result ? "成功" : "失败", "部门新增",
				ConstantMap.MODUAL_SYS_MGR, dept.toString()));
	}

	/**
	 * 页面跳转
	 *
	 * @return String
	 */
	@RequestMapping("/async")
	public String showDeptTree() {

		return "dept/testDemo";
	}

	@RequestMapping(value = "/delete/{deptId}")
	public String delete(@PathVariable("deptId") String deptId, ModelMap model) {
		List<SysDept> dept = sysDeptService.findDeptById(deptId);
		SysDept sysDept = null;
		if (dept.size() > 0)
			sysDept = dept.get(0);
		sysDeptService.deleteDeptByDeptId(deptId);
		Pagination<SysDept> page = sysDeptService.findDeptByPagination(deptId, 1);
		model.addAttribute("page", page);
		model.addAttribute(Constant.LOG_RECORD, new SysOperLog(Constant.DELETE, "成功", "部门删除",
				ConstantMap.MODUAL_SYS_MGR, sysDept.toString()));
		return "dept/deptInfo";
	}

	/**
	 * 部门机构编辑之后的保存
	 *
	 * @param dept
	 * @return
	 */
	@RequestMapping("/saveedit")
	public void saveEdit(ModelMap modelMap, SysDept dept) {
		int result = sysDeptService.saveEdit(dept);
		modelMap.addAttribute("success", result);
		modelMap.addAttribute(Constant.LOG_RECORD, new SysOperLog(Constant.UPDATE, 1 == result ? "成功" : "失败", "部门编辑",
				ConstantMap.MODUAL_SYS_MGR, dept.toString()));
	}

	/**
	 * 跳转到调整部门页面
	 *
	 * @return
	 */
	@RequestMapping("/changedept/{deptId}.html")
	public String gotochangedept(ModelMap modelMap, @PathVariable("deptId") String deptId, HttpServletRequest request) {
		SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
		List<String> deptIds = sysDeptService.findParents(deptId, user.getPoliceNum());
		modelMap.addAttribute("deptIds", deptIds);
		modelMap.addAttribute("deptId", deptId);
		return "dept/userChangeDept";
	}

	/**
	 * 查询一个部门下的所有人员
	 *
	 * @param modelMap
	 * @param request
	 */
	@RequestMapping("/getUsers")
	public void getAllUserByDept(ModelMap modelMap, HttpServletRequest request) {
		String deptId = request.getParameter("deptId");
		List<SysUser> users = sysDeptService.findUserByDeptId(deptId);
		modelMap.addAttribute("users", users);
		// modelMap.addAttribute(Constant.LOG_RECORD, new
		// SysOperLog(Constant.READ, "查看部门人员列表", ConstantMap.MODUAL_SYS_MGR,
		// ConstantMap.list2String(users)));
	}

	/**
	 * ajax删除部门
	 *
	 * @param modelMap
	 * @param request
	 */
	@RequestMapping("/deletedept/{deptId}")
	// public void deletedept(ModelMap modelMap, @PathVariable("deptId") String
	// deptId, @ModelAttribute(Constant.LOGIN_USER) SysUser user) {
	public void deletedept(ModelMap modelMap, @PathVariable("deptId") String deptId) {
		List<SysDept> dept = sysDeptService.findDeptById(deptId);
		SysDept sysDept = null;
		if (dept.size() > 0)
			sysDept = dept.get(0);
		int msg = sysDeptService.deleteDept(deptId);
		modelMap.addAttribute("msg", msg);
		modelMap.addAttribute(Constant.LOG_RECORD, new SysOperLog(Constant.DELETE, 0 == msg ? "成功" : "失败", "删除部门",
				ConstantMap.MODUAL_SYS_MGR, sysDept.toString()));
	}

	@RequestMapping("/updateorder")
	public void updateOrder(HttpServletRequest request, @ModelAttribute(Constant.LOGIN_USER) SysUser user,
							ModelMap model) {
		// 被拖动的id
		String deptId = request.getParameter("deptId");
		// 目标deptId
		String targetDeptId = request.getParameter("targetDeptId");
		sysDeptService.saveChangOrder(deptId, targetDeptId);
		model.addAttribute(Constant.LOG_RECORD, new SysOperLog(Constant.UPDATE, "成功", "部门拖动排序",
				ConstantMap.MODUAL_SYS_MGR, deptId + "   " + targetDeptId));
	}

	/**
	 * 委办局办理模块查询
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryorg/{deptId}/{pageIndex}.html")
	public String queryForContact(@PathVariable("deptId") String deptId, @PathVariable("pageIndex") int pageIndex,
								  ModelMap model) {
		Pagination<SysDept> page = sysDeptService.findNameByPagination(deptId, pageIndex);
		model.addAttribute("list", page);
		model.addAttribute("deptId", deptId);
		model.addAttribute("pageIndex", pageIndex);
		model.addAttribute(Constant.LOG_RECORD, new SysOperLog(Constant.READ, "查询部门列表", ConstantMap.MODUAL_SYS_MGR,
				ConstantMap.list2String(page.getList())));
		return "contact/dept_list";
	}

	@RequestMapping("/getchildren/{deptId}")
	public void findChildDept(@PathVariable("deptId") String deptId, ModelMap model) {
		List<SysDept> children = sysDeptService.findDeptByPid(deptId);
		model.addAttribute("depts", children);
		model.addAttribute(Constant.LOG_RECORD, new SysOperLog(Constant.READ, "查询部门列表", ConstantMap.MODUAL_SYS_MGR,
				ConstantMap.list2String(children)));
	}

}
